package com.chmingx.springcloud.controller;

import com.chmingx.springcloud.loadbalance.LoadBalancer;
import entities.CommonResult;
import entities.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
public class OrderController {
    private static final String PAYMENT_URL = "http://PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancer loadBalancer; // 注入自定义的负载均衡器
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/payment/create")
    public CommonResult<Integer> create(Payment payment) {
        // 返回对象为响应体中数据转化成的对象，基本上可以理解为Json
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        System.out.println(id);
        CommonResult<Payment> payment = restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, CommonResult.class);
        System.out.println(payment.getData());
        return payment;
    }

    @GetMapping("/consumer/payment/entity/{id}")
    public CommonResult<Payment> getPaymentEntity(@PathVariable("id") Long id) {
        // 返回对象为ResponseEntity对象，包含了响应中的一些重要信息，比如响应头，响应状态码，响应体等
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/" + id, CommonResult.class);
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        } else {
            return new CommonResult<>(444, "Fail");
        }
    }

    // 使用自定义的负载均衡算法
    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB() {
        List<ServiceInstance> instanceList = discoveryClient.getInstances("PAYMENT-SERVICE");
        if (instanceList == null || instanceList.size() <= 0) {
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instance(instanceList); // 使用自定义的负载均衡器
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);

    }
}
